import { Input } from "element-ui";
import slotsVnode from "@/components/mixins/slotsVnode";
import "./cInput.less";
/*
 * cInput 默认 maxlength为120
 * change触发自动讲value.trim()
 *  */

const customProps = {
  notMaxLength: Boolean, // 是否限制maxlength,为true则不限制maxlength
  /*
  * {
    min: 0,
    max: 1440,
    isInt: true, //是否只能输入正整数,值为int
  }
  *  */
  numberConfig: {
    type: Object,
    default: () => ({}),
  },
  notShowPlace: Boolean,
};
const cInput = {
  name: "cInput",
  props: {
    ...Input.props,
    size: {
      default: "small",
      type: String,
    },
    /* 以下为自定义props */
    ...customProps,
  },
  inheritAttrs: false,
  mixins: [slotsVnode],
  methods: {
    getInputRef(key) {
      // 获取el-input组件实例
      const res = this.$refs.elInput[key];
      if (res instanceof Function) {
        return res();
      }
      return res;
    },
    handlerInput(e) {
      const { isInt, max } = this.numberConfig;
      if (isInt) {
        // 正整数
        let val = e.replace(/[^\d]/g, ""); // 只能输入数字
        val = val.replace(/^0+(\d)/, "$1"); // 第一位0开头，0后面为数字，则过滤掉，取后面的数字
        val = val.replace(/(\d{15})\d*/, "$1"); // 最多保留15位整数
        val = val > max ? max : val;
        val = !val && val !== 0 ? undefined : +val;
        this.$emit("input", val);
        return;
      }
      this.$emit("input", e);
    },
    handlerChange(val) {
      let newVal = typeof val === "string" ? val.trim() : val;
      const { isInt } = this.numberConfig;
      if (isInt) {
        newVal = !newVal && newVal !== 0 ? undefined : +newVal;
      }
      this.$emit("input", newVal); // v-model使用的event是input
      this.$emit("change", newVal);
    },
  },
  render() {
    const { maxlength, placeholder } = this.$attrs;
    const newMaxlength = this.notMaxLength
      ? null
      : maxlength || maxlength === 0
      ? maxlength
      : 120; // 默认120长度,get接口搜索避免长度过大

    const newPlaceholder = placeholder
      ? placeholder
      : this.notShowPlace
      ? ""
      : "请输入内容";

    return (
      <Input
        ref="elInput"
        class={{ "show-word-limit": this.showWordLimit }}
        {...{
          props: {
            ...this.$props,
          },
          attrs: {
            ...this.$attrs,
            placeholder: newPlaceholder,
            maxlength: newMaxlength,
          },
          on: {
            ...this.$listeners,
            input: this.handlerInput,
            change: this.handlerChange,
          },
        }}
      >
        {this.slotsVnode()}
      </Input>
    );
  },
};
export default {
  install(Vue) {
    Vue.component(cInput.name, cInput);
  },
};
